//
//  PictureSelectorCollectionViewController.swift
//  ydy_weibo
//
//  Created by 杨德勇 on 16/7/17.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"
private let column:CGFloat = 4
private let pictureMargin :CGFloat = 10

private let maxImgCount = 9



class PictureSelectorCollectionViewController: UICollectionViewController {

    
    //MARK:-
    //MARK:重写init方法

    init(){
        let layout = UICollectionViewFlowLayout()
        //设置layout属性
        let width = (screenW - (column + 1) * pictureMargin) / column
        layout.itemSize = CGSize(width: width, height: width)
        layout.minimumInteritemSpacing = pictureMargin
        layout.minimumLineSpacing = pictureMargin
        //设置section间距
        layout.sectionInset = UIEdgeInsets(top: pictureMargin, left: pictureMargin, bottom: 0, right: pictureMargin)
        super.init(collectionViewLayout: layout)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

            }
    
    //MARK:-
    //MARK:数据源


    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
               return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = imageList.count == maxImgCount ? 0:1
        return imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        cell.selectorCellDelegate = self
        //cell.backgroundColor = UIColor.randomColor()
        
        if indexPath.item == imageList.count {
            cell.image = nil
        }else{
            cell.image = imageList[indexPath.item]
        }
    
        return cell
    }
    
    //MARK:-
    //MARK:懒加载属性
    lazy var imageList = [UIImage]()
    


    }


//MARK:-
//MARK:继承cell的代理协议
extension PictureSelectorCollectionViewController:PictureSelectorCellDelegate{
    func userWillAddPic(cell: PictureSelectorCell) {
        if cell.image != nil {return}
        
        //用系统的pickercontroller选择图片
        let picker = UIImagePickerController()
        picker.delegate = self
        
        //是否允许编辑(作为头像的时候要打开)
        //picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
        
        
    }
    
    func userWillDeletePic(cell: PictureSelectorCell) {
        let indexPath = self.collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex(indexPath!.item)
        
        //更新视图
        UIView.animateWithDuration(0.5, animations: { 
            cell.alpha = 0
            }) { (_) in
                cell.alpha = 1
                self.collectionView?.reloadData()
        }
    }
    
}

//MARK:-
//MARK:继承系统uiimagepicker的代理
extension PictureSelectorCollectionViewController:UIImagePickerControllerDelegate , UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //取到图片
        imageList.append(image)
        //刷新视图
        collectionView?.reloadData()
        //这个方法自己写的话，需要自己手动dismiss
        dismissViewControllerAnimated(true, completion: nil)
    }
}




//MARK:-
//MARK:自定义cell的协议
@objc protocol PictureSelectorCellDelegate:NSObjectProtocol{
    //新增图片
    optional func userWillAddPic(cell:PictureSelectorCell)
    //删除图片
    optional func userWillDeletePic(cell:PictureSelectorCell)
    
}


//MARK:-
//MARK:自定义cell类
class PictureSelectorCell : UICollectionViewCell {
    //定义代理属性,和图片属性
    weak var selectorCellDelegate:PictureSelectorCellDelegate?
    var image:UIImage?{
        didSet {
            deleteBtn.hidden = (image == nil)
            if image != nil {
                addBtn.setBackgroundImage(image, forState: .Normal)
            }else{
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
            
        }
    }
    
    
    
    //点击事件调用方法,执行代理
    @objc private func addBtnDidClick(){
        selectorCellDelegate?.userWillAddPic?(self)
        
        
    }
    @objc private func deleteBtnDidClick(){
        selectorCellDelegate?.userWillDeletePic?(self)
        
    }
    //重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        //约束
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.right.top.equalTo(contentView)
        }
        
        
        //添加点击事件
        addBtn.addTarget(self, action: #selector(self.addBtnDidClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(self.deleteBtnDidClick), forControlEvents: .TouchUpInside)
        
        
    }
   
    
    
    
    //定义cell中的基本属性（懒加载）
    private lazy var addBtn:UIButton = UIButton(title: nil, backimg: "compose_pic_add", color: nil)
    //不知道为什么这里设置背景图片会设置不上去，但是设置img就能设置上去了
    private lazy var deleteBtn:UIButton = UIButton(title: nil, backimg: "", color: nil, image: "compose_photo_close", fontsize: 19)
    //private lazy var deleteBtn:UIButton = UIButton(title: "啊", backimg: "compose_photo_close", color: UIColor.redColor())
    
}

